package dict;

import java.io.*;
import java.util.Arrays;

/**
 * Test counting lines of the index file in project Megadict.
 * 
 */

public class IndexLineCounter {

    public IndexLineCounter(File indexFile) {
        this.indexFile = indexFile;
    }

    public int countLine() {
        int numOfLines = 0;
        try {
            makeReader();

            while (stillAbleToRead()) {
                int numOfNewLineChar = countNewLineChar();
                numOfLines += numOfNewLineChar;
                resetBuffer();
            }
        } catch (FileNotFoundException fnf) {
            throw new RuntimeException(fnf);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }

        return numOfLines + 1;
    }

    private void makeReader() throws FileNotFoundException {
        reader = new BufferedReader(new FileReader(indexFile), READER_BUFFER_SIZE);
    }

    private boolean stillAbleToRead() throws IOException {
        return reader.read(charBuffer) != -1;
    }
    
    private void resetBuffer() {
        Arrays.fill(charBuffer, ' ');
    }

    private int countNewLineChar() {
        int count = 0;
        for (char c : charBuffer) {
            if (c == '\n') {
                count++;
            }
        }
        return count;
    }

    private File indexFile;
    private static final int READER_BUFFER_SIZE = 8 * 1024;
    private static final int BUFFER_SIZE = READER_BUFFER_SIZE / 2;

    private char[] charBuffer = new char[BUFFER_SIZE];
    private BufferedReader reader;
}
